import React, { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import Card from 'App/pages/SearchPage/components/Card';
import { useSearchPageStoreContext } from 'context/searchPageStore';
import { observer } from 'mobx-react-lite';
import moment from 'moment';
import RootStore from 'store/RootStore';

import { StarIcon } from 'components/icons';
import { classnames } from 'utils';

import classes from './OrgReposContainer.module.scss';

const cnOrgReposContainer = classnames(classes, 'orgReposContainer');

const OrgReposContainer: React.FC = () => {
    const navigate = useNavigate();
    const {
        searchPage: { currentPage },
        orgReposContainer: { setHashElement, orgRepos },
    } = useSearchPageStoreContext();

    const onClickCardHandle = useCallback(
        (owner: string, repo: string) => () => {
            RootStore.locationStore.setHash(repo);
            navigate(`/${owner}/${repo}`);
        },
        [],
    );

    return (
        <>
            {!!orgRepos.length && (
                <div className={cnOrgReposContainer()}>
                    {orgRepos.map(
                        (repo, repoIndex) =>
                            currentPage * 9 > repoIndex && (
                                <Card
                                    key={repo.id}
                                    id={repo.name}
                                    ref={RootStore.locationStore.hash === repo.name ? setHashElement : null}
                                    image={repo.ownerAvatarUrl}
                                    captionSlot={
                                        <div className={cnOrgReposContainer('card-captionSlot')}>
                                            <div className={cnOrgReposContainer('stargezers')}>
                                                <StarIcon className={cnOrgReposContainer('stargezers-icon')} />
                                                {repo.stargazersCount}
                                            </div>
                                            <p>{`Updated ${moment(repo.updatedAt).format('D MMM')}`}</p>
                                        </div>
                                    }
                                    title={repo.name}
                                    subtitle={repo.description}
                                    onClick={onClickCardHandle(repo.ownerLogin, repo.name)}
                                    className={cnOrgReposContainer('card')}
                                />
                            ),
                    )}
                </div>
            )}
        </>
    );
};

export default observer(OrgReposContainer);
